<template>
    <n-card :bordered="false" class="proCard">
        <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
            <n-input v-model:value="model[field]" />
        </template>
        </BasicForm>
        <BasicTable title="班级列表" titleTooltip="niconiconi" :columns="columns" :request="loadDataTable"
            :row-key="(row) => row.id" ref="actionRef" :actionColumn="actionColumn" :scroll-x="1360"
            :row-class-name="rowClassName" @update:checked-row-keys="onCheckedRow">
            <template #tableTitle>
            <n-space>
                <n-button type="primary" @click="addTable">
                    <template #icon>
                        <n-icon>
                            <PlusOutlined />
                        </n-icon>
                    </template>
                    新建
                </n-button>
                <n-button tag="a" type="primary" href="/api/index/getStudentExcelModel">
                    下载导入模板
                </n-button>
                </n-space>
            </template>
            <template #toolbar>
                <n-button type="primary" @click="reloadTable">刷新数据</n-button>
            </template>
        </BasicTable>
        <n-modal v-model:show="showModal" :show-icon="false" preset="dialog" :title="title">
            <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80"
                class="py-4">
                <n-form-item label="班级名" path="calseName">
                    <n-input placeholder="请输入班级名" v-model:value="formParams.claseName" />
                </n-form-item>
                <n-form-item label="学院名" path="academyName">
                    <n-select placeholder="请输入学院名" :options="academyMajorOptions" v-model:value="formParams.majorID" />
                </n-form-item>
                <n-form-item label="入学年份" path="enterYear">
                    <n-date-picker type='year' format='yyyy' placeholder="请输入入学年份" v-model:value="formParams.enterYear" />
                </n-form-item>
            </n-form>
            <template #action>
                <n-space>
                    <n-button @click="() => (showModal = false)">取消</n-button>
                    <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
                </n-space>
            </template>
        </n-modal>
        <n-modal v-model:show="showExcelModal" :show-icon="false" preset="dialog" title="Excel插入">
                <n-button
                    :disabled="!fileListLengthRef"
                    style="margin-bottom: 12px"
                    @click="uploadRef?.submit()"
                >
                    上传文件
                </n-button>
                <n-upload
                    ref="uploadRef"
                    :action="uploadUrl"
                    :default-upload="false"
                    :max="1"
                    @change="handleChange"
                    :headers="header"
                    @finish="handleUploadFinish"
                    @error="handleUploadError"
                >
                <n-button>选择文件</n-button>
            </n-upload>
            <template #action>
                <n-space>
                    <n-button @click="() => (showExcelModal = false)">取消</n-button>
                </n-space>
            </template>
        </n-modal>
    </n-card>
</template>
<script lang="ts" setup>
import { reactive, ref, h, onMounted } from 'vue';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getTableList } from '@/api/manager/claseManage/list';
import { BasicTable, TableAction } from '@/components/Table';
import { columns } from './clase';
import { PlusOutlined } from '@vicons/antd';
import { SelectOption, UploadFileInfo, UploadInst, useDialog, useMessage } from 'naive-ui';
import { http } from '@/utils/http/axios';
import { createStorage } from '@/utils/Storage';

const Storage = createStorage({ storage: localStorage });

const params = reactive({
    pageSize: 10
});
const showModal = ref(false);
const showExcelModal = ref(false);

const rules = [];
const formParams :any= reactive({
    claseID: null,
    claseName: null,
    majorID: null,
    enterYear: null
});
const formRef = ref();
const formBtnLoading = ref(false);
const title = ref("");

const message = useMessage();
const dialog = useDialog();
 const uploadRef = ref<UploadInst | null>(null)

 const fileListLengthRef = ref(0)

 const header={
    Authorization:Storage.get("ACCESS-TOKEN", ''),
 }

 const uploadUrl = ref("");

function confirmForm(e){
    e.preventDefault();
        formBtnLoading.value = true;
        formRef.value.validate((errors) => {
            if (!errors) {
            //message.success('新建成功');
            let params = formParams;
            params['enterYear'] = new Date(params['enterYear']).getFullYear();
            let url = '';
            if(title.value == "新建"){
                url = '/manager/clase_manage/addClase' 
            }else{
                url = '/manager/clase_manage/editClase'
            }
            http.request({
                url: url,
                method: 'post',
                params
            }).then(
                () => {
                message.success('成功');
                showModal.value = false;
                reloadTable();
                }
            );
            } else {
            message.error('请填写完整信息');
            }
            formBtnLoading.value = false;
        });
}

const loadDataTable = async (res) => {
    return await getTableList({ ...params, ...res });
};

const actionColumn = reactive({
    width: 150,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
        return h(TableAction, {
            style: 'button',
            actions: createActions(record),
        });
    },
});

function handleChange (options: { fileList: UploadFileInfo[] }) {
        fileListLengthRef.value = options.fileList.length
      }

const handleUploadFinish=({
      file,
      event
    }: {
      file: UploadFileInfo
      event?: ProgressEvent
    }) => {
      let response = JSON.parse((event?.target as XMLHttpRequest).response);
      if(response.code == 200){
        message.success("成功!");
        showExcelModal.value = false;
      }else{
        message.error(response.message);
      }
      reloadTable();
      return file
    }
function handleUploadError(){
    message.error('上传失败');
}

function handleDelete(record) {
    dialog.info({
        title: '提示',
        content: `您想删除${record.claseName}`,
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: () => {
            //message.success('删除成功');
            let getparam = {};
            let url="/manager/clase_manage/deleteClase";
            getparam['claseID'] = record['claseID'];
            http.request({
                url: url,
                method: 'get',
                params: getparam
            }
            ).then(
                () => {
                    message.success('成功');
                    reloadTable();
                }
            );
        },
        onNegativeClick: () => { },
    });
}

function handleEdit(row) {
    formParams.claseID = row.claseID;
    formParams.claseName = row.claseName;
    formParams.majorID = row.majorID;
    formParams.enterYear = new Date(row.enterYear+',1,1').getTime();
    title.value = '修改';
    showModal.value = true;
}

function handleExcel(record){
    showExcelModal.value = true;
    uploadUrl.value = '/api/manager/student_manage/excelInsertStudent?claseID='+record.claseID;
}


function rowClassName(row) {
    console.log(row);
    if (row.majorList != null) {
        return '';
    } else {
        return 'leaf-row'
    }
}

function createActions(record) {
    return [
        {
            label:'excel导入学生',
            type:'success',
            onclick:handleExcel.bind(null, record),
        },
        {
            label: '修改',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
                return true;
            },
            auth: ['basic_list'],
        }, {
            label: '删除',
            icon: 'ic:outline-delete-outline',
            onClick: handleDelete.bind(null, record),
            // 根据业务控制是否显示 isShow 和 auth 是并且关系
            ifShow: () => {
                return true;
            },
            // 根据权限控制是否显示: 有权限，会显示，支持多个
            auth: ['basic_list'],
        },

    ];
}
const actionRef = ref();
function onCheckedRow() {

}
function addTable() {
    formParams.claseID = null;
    formParams.claseName = null;
    formParams.majorID = null;
    formParams.enterYear = null;
    title.value = '新建';
    showModal.value = true;

}
function reloadTable() {
    actionRef.value.reload();
}
const academyMajorOptions = ref<SelectOption[]>([]);
onMounted(
  async () => {
    const academyMajorInfo = ref();
    academyMajorInfo.value = await http.request({
      url: '/manager/academy_major_manage/list',
      method: 'get',
    });
    academyMajorInfo.value.forEach(element => {
      academyMajorOptions.value.push({
        label: element['academyName'],
        key: element['academyID'],
        type: 'group',
        children: ((element) => {
          let arr: any = [];
          element['majorList'].forEach(element => {
            arr.push(
              {
                label: element['majorName'],
                value: element['majorID'],
              })
          });
          return arr;
        })(element),
      });
    });
    //获取学院信息
  })

const schemas: FormSchema[]=[
    {
        field: 'majorID',
        component:'NSelect',
        label:'专业',
        componentProps:{
            placeholder: '请选择专业',
            options: academyMajorOptions,
            onClear:()=>{
                params['majorID'] = null;
            }
        }
    },
    {
        field: 'enterYear',
        component: 'NDatePicker',
        label: '年级',
        componentProps: {
            placeholder: '请选择年级',
            type: 'year',
            format: 'yyyy',
            defaultValue: null,
        }
  }
];

const [register,{}] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:4 xl:5 2xl:5' },
  labelWidth: 80,
  schemas,
});

function handleSubmit(values: Recordable) {
  params['majorID'] = values['majorID'];
  if(values['enterYear']){
    params['enterYear'] = new Date(values['enterYear']).getFullYear()
  }else{
    params['enterYear']=null;
  }
  reloadTable();
}

function handleReset(values: Recordable) {
  console.log(values);
}

</script>